package geecache

import (
	"fmt"
	"geecache/consistenthhash"
	"net/http"
	"strings"
	"sync"
)

const DEFAULT_PATH_PREFIX = "/_geecache/"

type HTTPPool struct {
	self          string
	basePath      string
	nodeHashCycle *consistenthhash.HashCycle //hash环
	mu            sync.RWMutex
	nodes         map[string]PeerGetter //内部节点 节点标识 , 节点请求获取
}

func NewHttpPool(httpServerInfo string) *HTTPPool {
	r := HTTPPool{
		self:          httpServerInfo,
		basePath:      DEFAULT_PATH_PREFIX,
		nodeHashCycle: consistenthhash.NewCycle(nil, 10),
		nodes:         make(map[string]PeerGetter),
	}
	return &r
}

//Register 注册节点
func (h *HTTPPool) Register(hp HttpPeerGetter) {
	nodeKey := fmt.Sprintf("%s:%d", hp.service, hp.port)
	h.nodeHashCycle.Add(nodeKey)
	h.nodes[nodeKey] = hp
}

//RegisterNameNode 注册带名称的节点
func (h *HTTPPool) RegisterNameNode(node string, peer PeerGetter) {
	h.nodes[node] = peer
	h.nodeHashCycle.Add(node)
}

func (h *HTTPPool) ServeHTTP(writer http.ResponseWriter, request *http.Request) {
	writer.Header().Set("Content-Type", "text/plain;charset=UTF-8")
	url := request.URL.Path
	if strings.HasPrefix(url, h.basePath) {
		kvInfo := url[len(h.basePath):]
		kvParts := strings.Split(kvInfo, "/")
		partsLen := len(kvParts)
		if partsLen != 3 && partsLen != 2 {
			http.Error(writer, "错误的url格式", http.StatusBadRequest)
			return
		}
		groupName := kvParts[0]
		key := kvParts[1]
		if partsLen == 3 {
			//设置缓存
			if group, b := GetGroup(groupName); !b {
				http.Error(writer, "缓存组不存在", http.StatusNotFound)
			} else {
				value := kvParts[2]
				group.Add(key, []byte(value))
			}
		} else {
			//获取缓存
			if group, b := GetGroup(groupName); !b {
				NewGroup(groupName, nil)
				http.Error(writer, "缓存组不存在,已创建", http.StatusNotFound)
			} else {
				v, err := group.Get(key)
				if err != nil {
					http.Error(writer, "fmt.Sprintf(\"发生错误%s\\n\", err)", http.StatusInternalServerError)
				} else {
					writer.Write(v.b)
				}
			}
			return
		}
	} else {
		http.Error(writer, "不支持的接口", http.StatusBadRequest)
	}
}
